/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package demogroup5client.business;

import entity.Product;
import interfaces.LoadProductInterface;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author DungTV
 */
public class FilterBusiness {
    private final String portNumber= "2020";
    private final String naming ="loadproduct";
    private final String registryURL = "rmi://localhost:"+portNumber+"/"+naming;
    private LoadProductInterface loadProduct;

    public FilterBusiness() {
        this.registerHost();
    }

    public ArrayList<Product> filterProduct(ArrayList<Product> listProduct, String productName, String cat) {
        ArrayList<Product> list = listProduct;
        if (!productName.equals("")) {
            for (int i =0; i<list.size(); i++){
               Product p = list.get(i);
                if (!SubStr(productName,p.getProductName())) list.remove(p);
            }
            
        }
//        if (!cat.equals("")){
//           for(Product p : list){
//                if (!SubStr(cat,p.getCatID())) list.remove(p);
//            }
//        }
       
        return list;

    }

    private boolean SubStr(String subStr, String str) {
        String subS = subStr.trim();
        String s = str.trim();
        System.out.println("'"+subS+"'  '"+s+"'");
        
        if (s.lastIndexOf(subS)==-1){
            return false;
        } else return true;
    }




    private void registerHost() {
        try {
            loadProduct = (LoadProductInterface) Naming.lookup(registryURL);
        } catch (NotBoundException ex) {
            Logger.getLogger(FilterBusiness.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(FilterBusiness.class.getName()).log(Level.SEVERE, null, ex);
        } catch (RemoteException ex) {
            Logger.getLogger(FilterBusiness.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public ArrayList<Product> loadAllProduct(){
        try {
            return loadProduct.loadAllProduct();
        } catch (RemoteException ex) {
            Logger.getLogger(FilterBusiness.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
